package com.yhcnet.blog.service;

import com.yhcnet.blog.dao.UserMapper;
import com.yhcnet.blog.pojo.User;
import com.yhcnet.blog.reponse.UserBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service("userService")
public class UserService {
    @Autowired
    UserMapper userMapper;

    /**
     * 通过邮箱获取用户
     * @param email
     * @return
     */
    public User getUserByEmail(String email){
        return userMapper.getUserByEmail(email);
    }

    /**
     * 用户登录
     * @param userBody
     * @return
     */
    public String login(UserBody userBody){
        User user = new User();
        user.setEmail(userBody.getEmail());
        user.setPassword(userBody.getPassword());
        User login = userMapper.login(user);
        if(login != null){
            String uuid = UUID.randomUUID().toString();
            user.setUuid(uuid);
            int i = userMapper.updateUUID(user);
            if(i > 0) return uuid;
            return null;
        }
        return null;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    public synchronized boolean regist(User user){
        //首先先判断邮箱是否重复，如果重复，则失败
        if(user == null) return false;//参数空
        String email = user.getEmail();
        User userByEmail = getUserByEmail(email);
        if(userByEmail != null) return false;//邮箱重复
        int regist = userMapper.regist(user);
        if(regist > 0) return true;
        return false;
    }

    /**
     * 判断用户是否有权限
     * @param uuid
     * @return
     */
    public boolean judge(String uuid,String email){
        User judge = userMapper.judge(uuid);
        if(judge != null && judge.getEmail().equals(email)) return true;
        return false;
    }

    /**
     * 返回所有用户的信息，除了密码
     * @return
     */
    public List<User> getUser(){
        return userMapper.getUser();
    }
}
